Conditional (computer programming)
part 13/26 · 46.2 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
1
} else {
2
};
// This variant will not compile because 1 and () have different types
let my_variable = if x > 20 {
1
};
// Values can be omitted when not needed
if x > 20 {
println!("x is greater than 20");
}
Guarded conditionals
The Guarded Command Language (GCL) of Edsger Dijkstra supports conditional execution as a list of commands consisting of a Boolean-valued guard (corresponding to a condition) and its corresponding statement. In GCL, exactly one of the statements whose guards is true is evaluated, but which one is arbitrary. In this code
if G0 → S0
□ G1 → S1
...
□ Gn → Sn
fi
the Gi's are the guards and the Si's are the statements. If none of the guards is true, the program's behavior is undefined.
GCL is intended primarily for reasoning about programs, but similar notations have been implemented in Concurrent Pascal and occam.
Arithmetic if